/***********************************************************************************
 * 文件名： mcu_timer.c
 * 作者： 黄均铭
 * 版本： 1
 * 说明：
 * 		定时器驱动。
 * 修改记录：
 * 	2024年1月11日: 初版。 黄均铭。
 ***********************************************************************************/
#include "mcu_timer.h"
#include "mcu.h"

// 定时器初始化 TMR0 TMR1 TMR2 TMR3
void Tim_Init(TMR_T* timer)
{
    if (timer == TMR0)
    {
        TMR0->CON = TMR_CON_TMRMS_Msk | (TIM0_IE << TMR_CON_TMRIE_Pos) | (TIM0_PRS << TMR_CON_TMRPRE_Pos) | TMR_CON_TMRSZ_Msk;
        TMR0->LOAD = TIM0_CYCLE;

#if TIM0_IE != 0
        // 启动中断
        NVIC_EnableIRQ(TMR0_IRQn);
        NVIC_SetPriority(TMR0_IRQn, 3);
#endif

        TMR0->CON |= (TIM0_RUN << TMR_CON_TMREN_Pos);
    }
    else if (timer == TMR1)
    {
        TMR1->CON = TMR_CON_TMRMS_Msk | (TIM1_IE << TMR_CON_TMRIE_Pos) | (TIM1_PRS << TMR_CON_TMRPRE_Pos) | TMR_CON_TMRSZ_Msk;
        TMR1->LOAD = TIM1_CYCLE;

#if TIM1_IE != 0
        // 启动中断
        NVIC_EnableIRQ(TMR1_IRQn);
        NVIC_SetPriority(TMR1_IRQn, 3);
#endif

        TMR1->CON |= (TIM1_RUN << TMR_CON_TMREN_Pos);
    }
    else if (timer == TMR2)
    {
        TMR2->CON = TMR_CON_TMRMS_Msk | (TIM2_IE << TMR_CON_TMRIE_Pos) | (TIM2_PRS << TMR_CON_TMRPRE_Pos) | TMR_CON_TMRSZ_Msk;
        TMR2->LOAD = TIM2_CYCLE;

#if TIM2_IE != 0
        // 启动中断
        NVIC_EnableIRQ(TMR2_IRQn);
        NVIC_SetPriority(TMR2_IRQn, 3);
#endif

        TMR2->CON |= (TIM2_RUN << TMR_CON_TMREN_Pos);
    }
    else if (timer == TMR3)
    {
        TMR3->CON = TMR_CON_TMRMS_Msk | (TIM3_IE << TMR_CON_TMRIE_Pos) | (TIM3_PRS << TMR_CON_TMRPRE_Pos) | TMR_CON_TMRSZ_Msk;
        TMR3->LOAD = TIM3_CYCLE;

#if TIM3_IE != 0
        // 启动中断
        NVIC_EnableIRQ(TMR3_IRQn);
        NVIC_SetPriority(TMR3_IRQn, 3);
#endif

        TMR3->CON |= (TIM3_RUN << TMR_CON_TMREN_Pos);
    }
}

// 定时器周期值设置 TMR0 TMR1 TMR2 TMR3
void Tim_SetCycle(TMR_T* timer, u32 cycle)
{
    if (timer == TMR0)
    {
#if TIM0_RELOAD_MODE == 0
        TMR0->LOAD = cycle;
#else
        TMR0->BGLOAD = cycle;
#endif
    }
    else if (timer == TMR1)
    {
#if TIM1_RELOAD_MODE == 0
        TMR1->LOAD = cycle;
#else
        TMR1->BGLOAD = cycle;
#endif
    }
    else if (timer == TMR2)
    {
#if TIM2_RELOAD_MODE == 0
        TMR2->LOAD = cycle;
#else
        TMR2->BGLOAD = cycle;
#endif
    }
    else if (timer == TMR3)
    {
#if TIM3_RELOAD_MODE == 0
        TMR3->LOAD = cycle;
#else
        TMR3->BGLOAD = cycle;
#endif
    }
}

// 定时器当前计数值获取 TMR0 TMR1 TMR2 TMR3
u32 Tim_GetCycle(TMR_T* timer)
{
    return timer->VAL;
}
